package top.tanglizhi.springboot3.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.tanglizhi.springboot3.entity.user.AuthInfo;
import top.tanglizhi.springboot3.service.RedisService;
import top.tanglizhi.springboot3.util.IpUtils;

@Component
@Slf4j
@RequiredArgsConstructor
public class AppInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<AuthInfo> tl = new ThreadLocal<>();
    private final RedisService redisService;

    public static AuthInfo getAuthInfo() {
        return tl.get();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求拦截========================================================");
        log.debug("{}===>{}", request.getMethod(), request.getRequestURI());
        // 拦截控制器，获取授权信息
        if(handler instanceof HandlerMethod hm) {
           //保存认证信息
           AuthInfo authInfo = new AuthInfo();
           tl.set(authInfo);
          //token信息
          String token = request.getHeader("Authorization");
          token = token == null ? "" : token;
          authInfo.setToken(token);
          //获取用户id
          if (redisService.has(token)) {
              authInfo.setId(redisService.get(token, Integer.class));
          }
          // 请求信息
          authInfo.setIp(IpUtils.getIpAddress());
          authInfo.setMethod(request.getMethod());
          authInfo.setUrl(request.getRequestURI());
          // 控制器的mapping信息
          Class<?> clazz = hm.getBeanType();
          RequestMapping mapping = clazz.getAnnotation(RequestMapping.class);
          String value = mapping == null || mapping.value().length == 0 ? "" : mapping.value()[0];
          mapping = hm.getMethodAnnotation(RequestMapping.class);
          value += mapping == null || mapping.value().length == 0 ? "" : mapping.value()[0];
          authInfo.setMapping(value);
          log.debug("认证信息：{}", authInfo);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("后置拦截");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("拦截完毕=========================================================");
    }

}
